use strict;

package CGIUtils;
require Exporter;
use File::Basename;

=head1 NAME

CGIUtils - a small utilities for Meteosound cgi's

=head1 DESCRIPTION

read properties from $0.properties, print source, version , properties depending on the passed argument

=FUNCTIONS

=head3 init()

=EXPORTS

=head3 $query

the CGI current query object

=head3 %properties

A hash containing the properites key/values

=head1 COPYRIGHT

Copyright (C) 2004-2007  Alexandre Masselot

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

=head1 AUTHORS

Alexandre Masselot, www.framexpeditions.com

=cut

our ( @ISA, @EXPORT, @EXPORT_OK, $query, %properties );
my $propertiesFile;

@ISA = qw(Exporter);

@EXPORT    = qw($query %properties &init);
@EXPORT_OK = ();

sub init {
	$query = new CGI;
	$propertiesFile = "$0.properties";
	readProperties();

	if ( $query->param('version') ) {
		print $query->header( -type => 'text/plain' );
		undef $/;
		my $file = dirname($0) . "/VERSION";
		open( FD, "<$file" ) or die "cannot open file [$file]:$!";
		print <FD>;
		close FD;
		exit(0);
	}

	if ( $query->param('showsource') ) {
		print $query->header( -type => 'text/plain' );
		undef $/;
		open( FD, "<$0" ) or die "cannot open myself [$0]:$!";
		print <FD>;
		close FD;
		exit(0);
	}

	if ( $query->param('showproperties') ) {    
		print $query->header( -type => 'text/html' );
		print <<EOT;
    <h3>properties file in <i>$propertiesFile</i></h3>
    <pre>
EOT
		foreach ( sort keys %properties ) {
			print "<b>$_=</b>$properties{$_}\n";
		}
		print $query->end_html;
		exit(0);
	}

}

sub readProperties {
	open( FD, "<$propertiesFile" )
	  or die "cannot open for reading $propertiesFile: $!";
	while (<FD>) {
		chomp;
		s/\#.*//;
		next unless /([\w\.]+)=(.*?)\s*$/;
		$properties{$1} = $2;
	}
}

1;
